/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.earnings.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.api.utils.WithDrawUtil;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.earnings.entity.Earnings;
import com.jeeplus.modules.earnings.service.EarningsService;

/**
 * 收益记录Controller
 * @author zhych
 * @version 2021-08-18
 */
@RestController
@RequestMapping(value = "/earnings/earnings")
public class EarningsController extends BaseController {

	@Autowired
	private EarningsService earningsService;

	@Autowired
	private MemberService memberService;

	@ModelAttribute
	public Earnings get(@RequestParam(required=false) String id) {
		Earnings entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = earningsService.get(id);
		}
		if (entity == null){
			entity = new Earnings();
		}
		return entity;
	}

	/**
	 * 收益记录列表数据
	 */
	@RequiresPermissions("earnings:earnings:list")
	@GetMapping("list")
	public AjaxJson list(Earnings earnings, HttpServletRequest request, HttpServletResponse response) {
		Page<Earnings> page = earningsService.findPage(new Page<Earnings>(request, response), earnings);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取收益记录数据
	 */
	@RequiresPermissions(value={"earnings:earnings:view","earnings:earnings:add","earnings:earnings:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(Earnings earnings) {
		return AjaxJson.success().put("earnings", earnings);
	}

	/**
	 * 保存收益记录
	 */
	@RequiresPermissions(value={"earnings:earnings:add","earnings:earnings:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(Earnings earnings, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(earnings);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		earningsService.save(earnings);//保存
		return AjaxJson.success("保存收益记录成功");
	}


	/**
	 * 批量删除收益记录
	 */
	@RequiresPermissions("earnings:earnings:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			earningsService.delete(new Earnings(id));
		}
		return AjaxJson.success("删除收益记录成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("earnings:earnings:export")
    @GetMapping("export")
    public AjaxJson exportFile(Earnings earnings, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "收益记录"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Earnings> page = earningsService.findPage(new Page<Earnings>(request, response, -1), earnings);
    		new ExportExcel("收益记录", Earnings.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出收益记录记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("earnings:earnings:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Earnings> list = ei.getDataList(Earnings.class);
			for (Earnings earnings : list){
				try{
					earningsService.save(earnings);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条收益记录记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条收益记录记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入收益记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入收益记录数据模板
	 */
	@RequiresPermissions("earnings:earnings:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "收益记录数据导入模板.xlsx";
    		List<Earnings> list = Lists.newArrayList();
    		new ExportExcel("收益记录数据", Earnings.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 微信提现
	 * @param uid 提现用户
	 * @param money 提现金额
	 * @param remark 提现说明
	 * @return 提现结果
	 */
    @RequestMapping("withdraw")
	public AjaxJson withdraw(String uid, String money, String remark) throws Exception {
		// 查询该用户是否存在
		Member member = memberService.get(uid);
		if (StringUtils.isBlank(member.getOpenid())) {
			return AjaxJson.error("提现失败，该用户未授权");
		}
		// 查询该用户的余额
		if (new BigDecimal(member.getBalance()).compareTo(new BigDecimal(money)) < 0) {
			return AjaxJson.error("提现失败，余额不足");
		}
		if (new BigDecimal(money).compareTo(new BigDecimal("1")) < 0) {
			return AjaxJson.error("提现金额不能小于1元");
		}
		earningsService.withdraw(member, money, remark, appId, appSecret, mchNo, certPath);
		return AjaxJson.success("提现成功");
	}


}